package oc.tm.sg.core.loadbalance.policy;

import java.util.List;
import java.util.Random;

import oc.tm.sg.core.loadbalance.LoadBalance;
import oc.tm.sg.core.loadbalance.support.LoadServer;
import oc.tm.sg.registry.common.URL;

/**
 * 权重随机负载策略
 * @author lry
 */
@SuppressWarnings("rawtypes")
public class RandomLoadBalance implements LoadBalance<LoadServer<URL>> {

    public static final String NAME = "random";
    private final Random random = new Random();

	public LoadServer select(List<LoadServer<URL>> list){
    	if(list==null||list.size()==0){
    		return null;
    	}
        if(list.size()==1){
        	return list.get(0);
        }
        return doSelect(list);
	}
    
    protected LoadServer doSelect(List<LoadServer<URL>> list){
        int length=list.size();//总个数
        int totalWeight=0;//总权重
        boolean sameWeight=true;//权重是否都一样
        for(int i=0;i<length;i++){
            int weight=list.get(i).getWeight();
            totalWeight+=weight;//累计总权重
            if (sameWeight&&i>0&&weight!=list.get(i-1).getWeight()){
                sameWeight=false;//计算所有权重是否一样
            }
        }
        if(totalWeight>0&&!sameWeight){
            //如果权重不相同且权重大于0则按总权重数随机
            int offset=random.nextInt(totalWeight);
            //并确定随机值落在哪个片断上
            for(int i=0;i<length;i++){
                offset-=list.get(i).getWeight();
                if(offset<0){
                    return list.get(i);
                }
            }
        }
        // 如果权重相同或权重为0则均等随机
        return list.get(random.nextInt(length));
    }

}